package main

import (
	"gitee.com/kinwyb/appTools/appTool"
	"gitee.com/kinwyb/appTools/examples/src/assembly"
	"gitee.com/kinwyb/appTools/examples/src/rpc"
	"gitee.com/kinwyb/appTools/examples/src/rpc/serverRpc"
	"gitee.com/kinwyb/appTools/log"
	"github.com/emicklei/go-restful"
	"github.com/go-openapi/spec"
	restfulspec "github.com/kinwyb/go-restful-openapi"
	"net/http"
)

const appName = "examplesApi"

var app = appTool.NewApplication(appName)
var tcpServerAddr = ""

func init() {
	appTool.RegisterRestfulHttpContextParse(assembly.HttpRequestContextParse)
	appTool.RpcClientFunc = func() []appTool.RpcxClient {
		return []appTool.RpcxClient{
			&rpc.RpcxClient{},
		}
	}
}

func main() {
	//启动
	err := app.PrepareFunc(appPrepare).
		EnableApollo("common", "127.0.0.1:30071").
		InitRpcxClient().
		AfterFunc(func(app *appTool.Application) {
			app.Http().Swagger(&appTool.RestfulSwaggerConfig{
				Title:    "接口文件",
				Version:  appTool.Version,
				BasePath: "/v1/web",
				Host:     "127.0.0.1",
				Schemes:  []string{"http"},
			})
			initHttp(app.Http())
		}).Run()
	if err != nil {
		log.AppTool.Fatalf("运行结束:%s", err.Error())
	}
}

func appPrepare(app *appTool.Application) {
	log.AppTool.Debug("webapi启动")
	app.EnableHttp("0.0.0.0", 8080)
}

func initHttp(h *appTool.RestfulHttp) {
	//ws.Consumes(restful.MIME_JSON, restful.MIME_XML)
	ws.Produces(restful.MIME_JSON, restful.MIME_XML)
	ws.Path("/v1/web").Doc("示例接口")
	addRouter(examplesApiRouter, h)
	h.AddService(ws)
}

var ws = &restful.WebService{}

// 增加路由
func addRouter(fun func() *spec.Tag, a *appTool.RestfulHttp) {
	tag := fun()
	if tag != nil {
		a.SwaggerTag(*tag)
	}
}

// add
func addApi(rb *restful.RouteBuilder) *restful.RouteBuilder {
	return rb.Metadata(restfulspec.KeyOpenAPITags, []string{swaggerExamplesTag}).
		To(func(request *restful.Request, response *restful.Response) {
			resp := appTool.RestfulRequest(request, response)
			ret, err := serverRpc.Add(1, 2, resp.Context().(assembly.Context).Child())
			if err != nil {
				resp.Error(err)
				return
			}
			resp.Succ(ret)
		}).Returns(http.StatusOK, "结果", int64(0))
}

// add2
func add2Api(rb *restful.RouteBuilder) *restful.RouteBuilder {
	return rb.Metadata(restfulspec.KeyOpenAPITags, []string{swaggerExamplesTag}).
		To(func(request *restful.Request, response *restful.Response) {
			resp := appTool.RestfulRequest(request, response)
			ret, err := serverRpc.Add2(1, 2, resp.Context().(assembly.Context).Child())
			if err != nil {
				resp.Error(err)
				return
			}
			resp.Succ(ret)
		}).Do(appTool.RestfulApiResultDo)
}

const swaggerExamplesTag = "Examples"

func examplesApiRouter() *spec.Tag {
	ws.Route(addApi(ws.GET("/add").
		Doc("测试1")))
	ws.Route(add2Api(ws.GET("/add2").
		Doc("测试2")))
	// tag标签
	return &spec.Tag{TagProps: spec.TagProps{
		Name:        swaggerExamplesTag,
		Description: "示例"}}
}
